package com.glsc.ngateway.oaflow.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.dto.PageDto;
import com.glsc.ngateway.common.api.common.dto.PageQueryParamDto;
import com.glsc.ngateway.common.api.common.enums.ExceptionConstant;
import com.glsc.ngateway.common.api.common.enums.GatewayConstant;
import com.glsc.ngateway.common.api.oaflow.dto.FlowDetailFrontDto;
import com.glsc.ngateway.common.api.oaflow.dto.OaRequestLogResp;
import com.glsc.ngateway.common.api.oaflow.dto.SystemFlowStatisticsSearchParamDto;
import com.glsc.ngateway.common.api.oaflow.dto.VITSystemOAFlowResourceDto;
import com.glsc.ngateway.common.api.oaflow.dto.oa.OaParaDto;
import com.glsc.ngateway.common.api.oaflow.dto.oaflow.*;
import com.glsc.ngateway.common.api.oaflow.dto.oaform.FormInfoDto;
import com.glsc.ngateway.common.api.oaflow.dto.other.FlowObject;
import com.glsc.ngateway.common.api.oaflow.dto.param.ParamFlowSearchDto;
import com.glsc.ngateway.common.api.oaflow.resp.CommonResponse;
import com.glsc.ngateway.common.api.oaflow.resp.OaflowResponse;
import com.glsc.ngateway.common.base.converter.oaflow.WorkflowRequestbaseConverter;
import com.glsc.ngateway.common.base.domain.oracle.ecology.UFyyglzbszzszb;
import com.glsc.ngateway.common.base.domain.oracle.ecology.WorkflowRequestbase;
import com.glsc.ngateway.oaflow.exception.BusinessException;
import com.glsc.ngateway.oaflow.service.*;
import com.glsc.ngateway.oaflow.utils.DateUtils;
import com.glsc.ngateway.common.api.oaflow.resp.InterfaceResponse;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 这个Controller提供的服务供资管自研系统使用
 * <p>
 * 从原glsc_oagateway的FlowWorkController迁移过来
 * <p>
 * 对反馈对象做了修改，所以所有调用方如果要迁移有开发量
 */
@RestController
public class FlowController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AmqpTemplate rabbitTemplate;
    @Resource
    private MailService mailService;

    @Autowired
    FlowService flowService;

    @Autowired
    SwitchDataSourceService switchDataSourceService;

    @Autowired
    private MetaFlowService metaFlowService;
    @Autowired
    AddFlowService addFlowService;
    @Autowired
    AppendixService appendixService;


    @RequestMapping(method = RequestMethod.POST, value = "addDigitalCertificate")
    public String addDigitalCertificate(@RequestBody UFyyglzbszzszb uFyyglzbszzszb) {
        try {
            //通过kettle同步，不需要调用这个接口
//            flowService.addDigitalCertificate(uFyyglzbszzszb);
            return JSON.toJSONString(InterfaceResponse.returnSuccss("成功"));
        } catch (Exception e) {
            mailService.sendMailToAdmin("网关oaflow异常", Arrays.toString(e.getStackTrace()));
            logger.error("addDigitalCertificate异常!", e);
            return JSON.toJSONString(InterfaceResponse.returnError("失败"));
        }

    }


    /**
     * @param fileid
     * @param request
     * @return 从oa下载附件，供资管产品系统使用。
     * @throws IOException
     */
    @RequestMapping(value = "downloadSingleAppendix")
    public ResponseEntity<byte[]> downloadSingleAppendix(@RequestParam("fileid") String fileid, HttpServletRequest request) throws IOException {
        String urlInfo[] = appendixService.callAppendixService(fileid);
        logger.info("downloadUrl:" + urlInfo);
//        String[] urlarray = url[0].split("/");
        if (urlInfo != null) {
            String filename = urlInfo[1];
            String url = urlInfo[0];
            return appendixService.downSingleAppendixFromOA(url, filename, request);
        } else {
            return new ResponseEntity<byte[]>(null, new HttpHeaders(), HttpStatus.OK);
        }
    }

    /**
     * @param fileid
     * @param request
     * @return 从oa下载附件，供资管产品系统使用。
     * @throws IOException
     */
    @RequestMapping(value = "getDownloadAppendixInfo")
    public OaflowResponse<?> getDownloadAppendixInfo(@RequestParam("fileid") String fileid, HttpServletRequest request) throws IOException {
        String urlInfo[] = appendixService.callAppendixService(fileid);
        logger.info("downloadUrl:" + urlInfo);
//        String[] urlarray = url[0].split("/");
        if (urlInfo != null) {
//            String filename = urlInfo[1];
//            String url = urlInfo[0];
            return OaflowResponse.successData(urlInfo);
        } else {
            return OaflowResponse.failMsg("未获取信息");
        }
    }

    /**
     * @param fileid
     * @param response
     * @return 从oa下载附件，供资管产品系统使用。
     * @throws IOException
     */
    @RequestMapping(value = "downloadSingleAppendixNew")
    public ResponseEntity<byte[]> downloadSingleAppendixNew(@RequestParam("fileid") String fileid, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String urlInfo[] = appendixService.callAppendixService(fileid);
        logger.info("downloadUrl:" + urlInfo);
//        String[] urlarray = url.split("/");
        ResponseEntity<byte[]> result = null;
        if (urlInfo != null) {
            String filename = urlInfo[1];
            String url = urlInfo[0];
            result = appendixService.downSingleAppendixFromOANew(url, filename, request);

            try (OutputStream outputStream = response.getOutputStream()) {
                String fileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
                // filename*=utf-8'' 告诉浏览器以 utf-8 编码解码得到文件名字
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
                outputStream.write(result.getBody());
                outputStream.flush();
            } catch (Exception e) {
                logger.error("下载文件错误", e);
                return result;
            }
            return result;
        } else {
            return new ResponseEntity<byte[]>(null, new HttpHeaders(), HttpStatus.OK);
        }
    }


    /**
     * @param file
     * @return
     * @throws IOException
     * @description 上传附件
     */
    @RequestMapping(method = RequestMethod.POST, value = "/uploadDoc", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadDoc(@RequestPart(value = "file") MultipartFile[] file) throws IOException {
        logger.info("接收文件，并进行上传，时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        List<Map<String, String>> fileList = new ArrayList<Map<String, String>>();
        for (MultipartFile f : file) {
            Map appendixMap = new HashMap();
            appendixMap.put("annexName", f.getOriginalFilename());
            String appendixId = appendixService.updateAppendix(f.getOriginalFilename(), GatewayConstant.UP_FILE, f);
            logger.info("接收文件，并进行上传，文件名称:" + f.getOriginalFilename() + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
            appendixMap.put("annexId", appendixId);
            fileList.add(appendixMap);
        }
        logger.info("完成文件上传，时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        return JSON.toJSONString(InterfaceResponse.returnSuccss(fileList));
    }

    /**
     * 原接口：addNoContractApprovalFlow
     */
    @RequestMapping(value = "addNoContractApprovalFlow")
    public String addNoContractApprovalFlow(@RequestBody Map<String, Object> dataMap, @RequestParam("flowId") String flowId,
                                            @RequestParam(value = "subscribe", required = false) boolean subscribe) throws Exception {
        return this.createOaflow(dataMap, flowId, null, subscribe);
    }

    @RequestMapping(value = "endOaFlow")
    public String endOaFlow(@RequestParam("requestId") String requestId) {
        Map<String, String> map = addFlowService.endOaFlow(requestId);
        return JSON.toJSONString(InterfaceResponse.returnSuccss(map));
    }

    /**
     * 功能说明：新增流程 调用oa
     * <p>
     * 原接口：addNoContractApprovalFlow
     */
    @RequestMapping(value = "createOaflow")
    public String createOaflow(@RequestBody Map<String, Object> dataMap, @RequestParam("flowId") String flowId,
                               @RequestParam(value = "isnextflow", defaultValue = "0", required = false) String isnextflow,
                               @RequestParam(value = "subscribe", required = false) boolean subscribe) throws Exception {

        logger.info("开始创建流程，FlowId:" + flowId + ",参数:" + dataMap.toString() + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        String params = "flowId:" + flowId;
        //取得主必填字段，字段名称为转义后的
        Set<String> fields = metaFlowService.getMandatoryFields(flowId, "0");
        logger.debug("外层：" + fields.toString());
        //取得必填的明细字段，字段名称为转义后的
        Map<String, Set<String>> detailFields = metaFlowService.getMandatoryDetails(flowId);
        logger.debug("内层：" + detailFields.toString());
        //校验必填参数
        String paramsVerfication = metaFlowService.checkFLowParams(dataMap, fields, detailFields);

        Assert.isTrue(paramsVerfication.equals(GatewayConstant.PARAMS_VERIFICATION), () -> {
            logger.error("创建流程失败，FlowId:" + flowId + ",关键参数缺失:" + paramsVerfication + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
            throw new BusinessException(ExceptionConstant.BussinessException, "创建流程失败，流程ID:" + flowId + " ,缺失参数:" + paramsVerfication);
        });
        //组装创建流程请求报文
        FlowObject fo = addFlowService.operateOAMessage(dataMap, metaFlowService.getFlowMetaDataList(flowId), flowId);
        fo.setIsnextflow(isnextflow);
        logger.info("创建流程调用参数为：" + JSONObject.toJSON(fo).toString());
        //调oa创建接口
        Map<String, String> resultMap = addFlowService.addOaFlow(JSONObject.toJSON(fo).toString(), subscribe);
        Assert.isTrue(Integer.parseInt(resultMap.get("requestid")) > 0, () -> {
            logger.error("流程创建失败，FlowId:" + flowId + ",流程requestid:" + resultMap.get("requestid") + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
            throw new BusinessException(ExceptionConstant.BussinessException, "创建流程失败，需要咨询OA系统，流程ID:" + flowId + ",参数:" + dataMap);
        });
        logger.info("完成流程创建，FlowId:" + flowId + ",流程requestid:" + resultMap.get("requestid") + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        return JSON.toJSONString(InterfaceResponse.returnSuccss(resultMap));
    }

    /**
     * 创建oa流程  必须传公司和部门信息
     *
     * @param dataMap
     * @param flowId
     * @param isnextflow
     * @param subscribe
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "createOaflowWithDeptId")
    public String createOaflowWithDeptId(@RequestBody Map<String, Object> dataMap, @RequestParam("flowId") String flowId,
                                         @RequestParam(value = "isnextflow", defaultValue = "0", required = false) String isnextflow,
                                         @RequestParam(value = "subscribe", required = false) boolean subscribe) throws Exception {

        logger.info("开始创建流程，FlowId:" + flowId + ",参数:" + dataMap.toString() + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        String params = "flowId:" + flowId;
        //取得主必填字段，字段名称为转义后的
        Set<String> fields = metaFlowService.getMandatoryFields(flowId, "0");
        logger.debug("外层：" + fields.toString());
        //取得必填的明细字段，字段名称为转义后的
        Map<String, Set<String>> detailFields = metaFlowService.getMandatoryDetails(flowId);
        logger.debug("内层：" + detailFields.toString());
        //校验必填参数
        String paramsVerfication = metaFlowService.checkFLowParams(dataMap, fields, detailFields);

        Assert.isTrue(paramsVerfication.equals(GatewayConstant.PARAMS_VERIFICATION), () -> {
            logger.error("创建流程失败，FlowId:" + flowId + ",关键参数缺失:" + paramsVerfication + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
            throw new BusinessException(ExceptionConstant.BussinessException, "创建流程失败，流程ID:" + flowId + " ,缺失参数:" + paramsVerfication);
        });
        //组装创建流程请求报文
        FlowObject fo = addFlowService.operateOAMessageWithDeptId(dataMap, metaFlowService.getFlowMetaDataList(flowId), flowId);
        fo.setIsnextflow(isnextflow);
        logger.info("创建流程调用参数为：" + JSONObject.toJSON(fo).toString());
        //调oa创建接口
        Map<String, String> resultMap = addFlowService.addOaFlow(JSONObject.toJSON(fo).toString(), subscribe);
        Assert.isTrue(Integer.parseInt(resultMap.get("requestid")) > 0, () -> {
            logger.error("流程创建失败，FlowId:" + flowId + ",流程requestid:" + resultMap.get("requestid") + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
            throw new BusinessException(ExceptionConstant.BussinessException, "创建流程失败，需要咨询OA系统，流程ID:" + flowId + ",参数:" + dataMap);
        });
        logger.info("完成流程创建，FlowId:" + flowId + ",流程requestid:" + resultMap.get("requestid") + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        return JSON.toJSONString(InterfaceResponse.returnSuccss(resultMap));
    }

    /**
     * 原始版，不做转换
     *
     * @param param
     * @param flowId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "createOaflowOrigin")
    public String createOaflowOrigin(@RequestBody String param, @RequestParam("flowId") String flowId, @RequestParam(value = "subscribe", required = false) boolean subscribe) throws Exception {
        logger.info("开始创建流程原始版，FlowId:" + flowId + ",参数:" + param + ",时间:" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        Map<String, String> resultMap = addFlowService.addOaFlow(param, subscribe);
        return JSON.toJSONString(InterfaceResponse.returnSuccss(resultMap));
    }

    @RequestMapping(value = "getRequestDataOrigin", produces = {"application/json"})
    public String getRequestDataOrigin(@RequestParam("workflowId") String workflowId,
                                       @RequestParam("requestId") String requestId,
                                       @RequestParam(value = "flowStatus", defaultValue = "", required = false) String flowStatus) {
        List<Map<String, String>> dataMap = flowService.getRequestDataOrigin(workflowId, requestId, flowStatus);
        return JSON.toJSONString(InterfaceResponse.returnSuccss(dataMap));
    }

    @RequestMapping(value = "downloadAppendix")
    public ResponseEntity<byte[]> downloadAppendix(@RequestParam("requestId") String requestId, @RequestParam("flowId") String flowId, HttpServletRequest request) throws IOException {
        String params = "requestId:" + requestId + ",flowId:" + flowId;
        List<String[]> listUrl = appendixService.getAllFlowDocIds(requestId, flowId);
        String targetName = GatewayConstant.DOWNLOAD_FILE + UUID.randomUUID() + ".zip";
        logger.info("listUrl:" + listUrl.size());
        if (listUrl.size() > 0) {
            return appendixService.downAllAppendix(listUrl, targetName, request);
        } else {
            return new ResponseEntity<byte[]>(null, new HttpHeaders(), HttpStatus.OK);
        }
    }

    /**
     * 股衍增量查询流程附件查询接口
     *
     * @param appendixType 流程表单附件类别名称：多个英文逗号分隔*
     */
    @RequestMapping(value = "isExistAppendix")
    public OaflowResponse<Map<String, Object>> isExistAppendix(@RequestParam("requestId") String requestId,
                                                               @RequestParam("appendixType") String appendixType,
                                                               @RequestParam("callSystemId") String callSystemId,
                                                               @RequestParam("isForce") String isForce) {
        String params = "requestId:" + requestId + ",callSystemId:" + callSystemId + ",isForce:" + isForce;
        logger.info(params);
        if (!flowService.hasWorkFlowRequestBase(List.of(Integer.valueOf(requestId)))) {
            return OaflowResponse.failData(Map.of("msg", "requestId不存在，OA流程已删除"));
        }

        List<String> appendixTypeList = Arrays.stream(appendixType.split(",")).collect(Collectors.toList());
        Map<String, Object> resultMap = appendixService.isExistAppendix(requestId, appendixTypeList, callSystemId, isForce);
        resultMap.put("appendixType", appendixType);//整体下载附件的情况
        return OaflowResponse.successData(resultMap);
    }

    /**
     * 股衍增量查询流程附件下载
     *
     * @param appendixType 流程表单附件类别名称：多个英文逗号分隔*
     */
    @RequestMapping(value = "downloadDerivativeAppendix")
    public ResponseEntity<byte[]> downloadDerivativeAppendix(@RequestParam("requestId") String requestId,
                                                             @RequestParam("appendixType") String appendixType,
                                                             HttpServletRequest request) throws IOException {
        String params = "requestId:" + requestId + ",appendixType:" + appendixType;
        List<String> appendixTypeList = Arrays.stream(appendixType.split(",")).collect(Collectors.toList());

        int workFlowId = flowService.getWorkflowIdByRequestId(requestId);
        if (workFlowId < 1) {
            throw new RuntimeException("未找到流程实例对应的流程类型信息");
        }

        List<String[]> listUrl = new ArrayList<>();

        for (String appendixTypeTmp : appendixTypeList) {
            List<String[]> tempList = appendixService.getDerivativeFlowDocIds(requestId, String.valueOf(workFlowId), appendixTypeTmp);
            if (CollectionUtil.isNotEmpty(tempList)) {
                listUrl.addAll(tempList);
            }
        }

        logger.info("listUrl:" + listUrl.size());
        String targetName = GatewayConstant.DOWNLOAD_FILE + UUID.randomUUID() + ".zip";
        if (listUrl.size() > 0) {
            return appendixService.downAllAppendix(listUrl, targetName, request);
        } else {
            return new ResponseEntity<byte[]>(null, new HttpHeaders(), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "getRequestData", produces = {"application/json"})
    public String getRequestDataNew(@RequestParam("requestId") String requestId,
                                    @RequestParam(value = "flowStatus", defaultValue = "", required = false) String flowStatus) throws Exception {
        List<Map<String, String>> dataMap = flowService.getRequestDataNew(requestId, flowStatus);
        return JSON.toJSONString(InterfaceResponse.returnSuccss(dataMap));
    }

    @RequestMapping(value = "getRequestBase")
    public CommonResponse<List<WorkflowRequestbaseDto>> getRequestDataNew(@RequestBody List<String> requestId) {
        return CommonResponse.success(WorkflowRequestbaseConverter.do2Dto(flowService.getRequestBaseInfo(requestId.stream().map(Integer::parseInt).collect(Collectors.toList()))));
    }

    /**
     * 查询OA流程实例基础信息
     */
    @RequestMapping(value = "getRequestBaseInfo", produces = {"application/json"})
    public CommonResponse<WorkflowRequestbase> getRequestBaseInfo(@RequestParam("requestId") int requestId) {
        WorkflowRequestbase requestBaseInfo = flowService.getRequestBaseInfo(requestId);
        return CommonResponse.success(requestBaseInfo);
    }

    @RequestMapping(value = "getWorkflowBase", produces = {"application/json"})
    public String getWorkflowBase(@RequestParam(value = "workflowName", defaultValue = "", required = false) String workflowName) {
        List<Map<String, Object>> dataMap = flowService.getWorkflowBase(workflowName);
        return JSON.toJSONString(InterfaceResponse.returnSuccss(dataMap));
    }

    @RequestMapping(value = "pageWorkflowBase", produces = {"application/json"})
    CommonResponse<PageDto<WorkflowBaseDto>> pageWorkflowBase(@RequestBody PageQueryParamDto<WorkflowBaseQueryParamDto> param) {
        return CommonResponse.success(flowService.pageWorkflowBase(param));
    }

    @RequestMapping(value = "getWorkflowRequestBase", produces = {"application/json"})
    public String getWorkflowRequestBase(@RequestParam("beginDate") String beginDate,
                                         @RequestParam("endDate") String endDate,
                                         @RequestParam(value = "workflowId", defaultValue = "", required = false) String workflowId) {
        List<Map<String, Object>> dataMap = flowService.getWorkflowRequestBase(beginDate, endDate, workflowId);
        return JSON.toJSONString(InterfaceResponse.returnSuccss(dataMap));
    }

    //****************************************************以下方法准备废弃************************************************

    /**
     * 功能说明：
     * 依据流程ID获取流程所有节点信息
     * <p>
     * 调用说明：
     * 这个接口目前没有使用
     * <p>
     * ATTENTION：
     * WorkflowRequestbase对象中套了一个Hrmresource对象，可以获取执行人相关的具体信息
     */
    @RequestMapping(value = "getWorkFlowInfos")
    public OaflowResponse<Map<String, Object>> getWorkFlowInfos(@RequestParam("requestId") Long requestId) {
        if (!flowService.hasWorkFlowRequestBase(List.of(requestId.intValue()))) {
            return OaflowResponse.failData(Map.of("msg", "requestId不存在，OA流程已删除"));
        }
        List<Map<String, Object>> dataList = flowService.getWorkFlowInfos(List.of(requestId));
        return OaflowResponse.successData(CollectionUtil.isNotEmpty(dataList) ? dataList.get(0) : Collections.EMPTY_MAP);
    }

    @PostMapping(value = "getWorkFlowInfosBatch")
    public OaflowResponse<List<Map<String, Object>>> getWorkFlowInfosBatch(@RequestBody List<Long> requestIds) {
        if (CollectionUtil.isEmpty(requestIds)) {
            return OaflowResponse.successData(Lists.newArrayList());
        }
        List<Integer> ids = Lists.newArrayList();
        for (Long requestId : requestIds) {
            ids.add(requestId.intValue());
        }
        if (!flowService.hasWorkFlowRequestBase(ids)) {
            return OaflowResponse.failData(List.of(Map.of("msg", "requestId不存在，OA流程已删除")));
        }
        return OaflowResponse.successData(flowService.getWorkFlowInfos(requestIds));
    }

    /**
     * 功能说明：
     * 依据流程ID获取流程当前状态
     * <p>
     * 调用说明：
     * 这个接口被股衍和产品管理使用
     * <p>
     * ATTENTION：
     * 原服务是返回：WORKFLOW_REQUESTBASE表的所有字段信息
     * 需要跟调用方确认状态用的是：status or currentstatus or Currentnodetype
     */
    @RequestMapping(value = "getWorkFlowStatus")
    public OaflowResponse<Map<String, Object>> getWorkFlowStatus(@RequestParam("requestId") Integer requestId) {
        if (!flowService.hasWorkFlowRequestBase(List.of(requestId))) {
            return OaflowResponse.failData(Map.of("msg", "requestId不存在，OA流程已删除"));
        }
        List<Map<String, Object>> dataList = flowService.getWorkFlowCurrentStatus(List.of(requestId));
        return OaflowResponse.successData(CollectionUtil.isNotEmpty(dataList) ? dataList.get(0) : Collections.EMPTY_MAP);
    }

    @PostMapping(value = "getWorkFlowStatusBatch")
    public OaflowResponse<List<Map<String, Object>>> getWorkFlowStatusBatch(@RequestBody List<Integer> requestId) {
        if (!flowService.hasWorkFlowRequestBase(requestId)) {
            return OaflowResponse.failData(List.of(Map.of("msg", "requestId不存在，OA流程已删除")));
        }
        return OaflowResponse.successData(flowService.getWorkFlowCurrentStatus(requestId));
    }
//
//
//    /**
//     * 功能说明：
//     * 用于查询特定流程的要素信息
//     * <p>
//     * 调用说明：
//     * OA会在发现一个流程状态为结束的时候，会通过调用forwardOARequest服务告知网关,内容包含requestId
//     * 网关将消息放入延迟队列，通知glamdata
//     * glamdata会在收到消息的时候通过调用本接口获取特定流程的要素信息
//     * <p>
//     * workflowId=1088105 requestId Q中推送消息告知 flowStatus=3
//     * oaWorkflowResponse = fofWorkflowClient.getDataViaRequestId(workflowId, id, flowStatus);
//     * <p>
//     * ATTENTION：
//     * 返回结果做了一些转换：
//     * 1.所有结果平铺开，没有table套detailTable（detailMap）这种结构了
//     * 2.暂未提供doc转换
//     * <p>
//     * 逻辑上做了一些转换：
//     * 1.从OA上获取流程信息，如果t_oa_flow_meta_table表中没有做配置，还是会正常返回。（日志有提醒）
//     * 2.t_oa_flow_meta_table表中field_type在该服务里没有用处了。（结果平铺，没有层级关系）
//     */
//    //@RequestMapping(value = "getRequestData")
//    public String getRequestData(@RequestParam("workflowId") String workflowId,
//                                 @RequestParam("requestId") String requestId,
//                                 @RequestParam(value = "flowStatus", defaultValue = "", required = false) String flowStatus) {
//
//        List<Map<String, Object>> dataMap = flowService.getRequestData(Integer.parseInt(workflowId), Integer.parseInt(requestId), flowStatus);
//        return JSON.toJSONString(InterfaceResponse.returnSuccss(dataMap));
//    }


    //    /**
//     * @return
//     * @Description 供第三方系统调用，同步节点状态
//     */
//    @RequestMapping(value = "synchronizedTask")
//    public String synchronizedTask(@RequestParam("workflowId") String workflowId,
//                                   @RequestParam("requestId") String requestId,
//                                   @RequestParam("workflowName") String workflowName,
//                                   @RequestParam("status") String status,
//                                   @RequestParam("comment") String comment, @RequestParam("sysid") String sysid) {
//        String params = "workflowId:" + workflowId + ",requestId:" + requestId + ",workflowName:" + workflowName
//                + ",status:" + status + ",comment:" + comment + ",sysid:" + sysid;
//        interfaceService.insertInterfaceHistory(params, "第三方系统同步节点状态");
//
//
//        Map<String, String> messageMap = new HashMap<>();
//        messageMap.put("workflowId", workflowId);
//        messageMap.put("requestId", requestId);
//        messageMap.put("workflowName", workflowName);
//        String message = JSONObject.toJSONString(messageMap);
//
//        TOaFlowMessageTable oaFlowMessage = new TOaFlowMessageTable();
//        oaFlowMessage.setRequestIdOther(requestId);
//        oaFlowMessage.setWorkFlowIdOther(workflowId);
//        oaFlowMessage.setWorkFlowName(workflowName);
//        oaFlowMessage.setComment(comment);
//        oaFlowMessage.setStatus(status);
//        oaFlowMessage.setSysid(sysid);
//        Boolean result = flowService.insertOaMessage(oaFlowMessage);
//        if (result) {
//            logger.info("Success! 第三方系统同步节点状态写入数据库成功，参数:" + params);
//        } else {
//            logger.error("Error! 第三方系统同步节点状态写入数据库失败，参数:" + params);
//        }
//        return JSON.toJSONString(InterfaceResponse.returnSuccss("requestId为'" + requestId + "'的流程流转信息推送成功"));
//    }

    @RequestMapping(method = RequestMethod.GET, value = "getWorkFlowOaPicData")
    public FlowDetailFrontDto getWorkFlowOaPicData(@RequestParam("requestId") Integer requestId) {
        logger.info("查询OA流程数据,requestID：{}", requestId);
        FlowDetailFrontDto res = flowService.getWorkFlowOaPicData(requestId);
        return res;
    }

    @RequestMapping(method = RequestMethod.GET, value = "getWorkFlowOaFormInfo")
    public CommonResponse<List<FormInfoDto>> getWorkFlowOaFormInfo(@RequestParam("workflowId") String workflowId) {
        logger.info("查询OA流程表单信息,workflowId：{}", workflowId);
        return CommonResponse.success(flowService.getWorkFlowOaFormInfo(workflowId));
    }

    @RequestMapping(method = RequestMethod.GET, value = "getWorkFlowOaFormDictInfo")
    public CommonResponse getWorkFlowOaFormDictInfo(@RequestParam("workflowId") String workflowId) {
        logger.info("查询OA流程表单字典信息,workflowId：{}", workflowId);
        return CommonResponse.success(flowService.getWorkFlowOaFormDictInfo(workflowId));
    }

    @RequestMapping(method = RequestMethod.GET, value = "getWorkFlowOaMainTableField")
    public CommonResponse getWorkFlowOaMainTableField(@RequestParam("requestId") Integer requestId) {
        logger.info("查询OA流程表单字典信息,requestID：{}", requestId);
        return CommonResponse.success(flowService.getWorkFlowOaMainTableField(requestId));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getRequestLogList")
    public CommonResponse<OaRequestLogResp> getRequestLogList(@RequestParam("requestId") Integer requestId,
                                                              @RequestParam(value = "account", required = false) List<String> roleList) throws Exception {
        logger.info("查询OA流程表单签字意见信息,requestID：{}, roleList:{}", requestId, roleList);
        return CommonResponse.success(flowService.getRequestLogList(requestId, roleList));
    }

    @RequestMapping(method = RequestMethod.POST, value = "updateWorkFlowConfig")
    public CommonResponse<Boolean> updateWorkFlowConfig(@RequestBody List<WorkFlowRelation> workFlowRelList) {
        try {
            flowService.updateWorkFlowConfig(workFlowRelList);
            return CommonResponse.success(Boolean.TRUE);
        } catch (Exception e) {
            logger.error("updateWorkFlowConfig!", e);
            return CommonResponse.error(e.getMessage());
        }

    }

    /**
     * 获取非合同审批
     *
     * @param param
     * @return
     */

    @RequestMapping(method = RequestMethod.POST, value = "/getOaNoContractApproval")
    public CommonResponse<Object> getOaNoContractApproval(@RequestBody OaParaDto param) {
        logger.info("getOaNoContractApproval,param：{}", param);
        Assert.notNull(param.getApplyDateBegin(), "开始日期为空");
        Assert.notNull(param.getApplyDateEnd(), "结束日期为空");
        return CommonResponse.success(flowService.getOaNoContractApproval(param));
    }

    /**
     * 获取合同流程
     *
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/getOaContract")
    public CommonResponse<Object> getOaContract(@RequestBody OaParaDto param) {
        logger.info("getOaContract,param：{}", param);
        Assert.notNull(param.getApplyDateBegin(), "开始日期为空");
        Assert.notNull(param.getApplyDateEnd(), "结束日期为空");
        return CommonResponse.success(flowService.getOaContract(param));
    }

    /**
     * 获取09.资金运营部内部用印审批流程
     *
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/getOaInnerStampApproval")
    public CommonResponse<Object> getOaInnerStampApproval(@RequestBody OaParaDto param) {
        logger.info("getOaInnerStampApproval,param：{}", param);
        Assert.notNull(param.getApplyDateBegin(), "开始日期为空");
        Assert.notNull(param.getApplyDateEnd(), "结束日期为空");
        return CommonResponse.success(flowService.getOaInnerStampApproval(param));
    }

    @RequestMapping(method = RequestMethod.GET, value = "getSystemOaFlowPage")
    public CommonResponse<PageDto<VITSystemOAFlowResourceDto>> getSystemOaFlowPage(@RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize, @RequestParam("systemClassNo") String systemClassNo) {
        logger.info("查询OA流程表单关联的系统编号,systemClassNo：{}", systemClassNo);
        return CommonResponse.success(flowService.getOAFlowListBySystemClassNo(pageNo, pageSize, systemClassNo));
    }

    @RequestMapping(method = RequestMethod.POST, value = "getSystemOaFlowList")
    public CommonResponse<List<VITSystemOAFlowResourceDto>> getSystemOaFlowList(@RequestBody ParamFlowSearchDto params) {
        logger.info("查询OA流程表单关联的系统编号,systemClassNo：{}", params.getSystemClassNo());
        List<VITSystemOAFlowResourceDto> oaFlowList = flowService.getOAFlowList(params);
        return CommonResponse.success(oaFlowList);
    }

    /**
     * 获取03.股衍业务资金划拨流程
     *
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/getOaMoneyTransfer")
    public CommonResponse<Object> getOaMoneyTransfer(@RequestBody OaParaDto param) {
        logger.info("getOaMoneyTransfer,param：{}", param);
        Assert.notNull(param.getApplyDateBegin(), "开始日期为空");
        Assert.notNull(param.getApplyDateEnd(), "结束日期为空");
        return CommonResponse.success(flowService.getOaMoneyTransfer(param));
    }

    /**
     * 获取10.基金申赎流程
     *
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/getOaFundBuy")
    public CommonResponse<Object> getOaFundBuy(@RequestBody OaParaDto param) {
        logger.info("getOaFundBuy,param：{}", param);
        Assert.notNull(param.getApplyDateBegin(), "开始日期为空");
        Assert.notNull(param.getApplyDateEnd(), "结束日期为空");
        return CommonResponse.success(flowService.getOaFundBuy(param));
    }

    /**
     * 获取10.基金申赎流程
     *
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getCustomRateChange")
    public CommonResponse<Object> getCustomRateChange(@RequestParam("flowtype") String flowtype,
                                                      @RequestParam(value = "applyDateBegin", required = false) String applyDateBegin,
                                                      @RequestParam(value = "applyDateEnd", required = false) String applyDateEnd
                                                      ) {
        logger.info("getCustomRateChange,param：{},{},{}", flowtype,applyDateBegin,applyDateEnd);
        Assert.notNull(flowtype, "类型为空");
        return CommonResponse.success(flowService.getCustomRateChange(flowtype,applyDateBegin,applyDateEnd));
    }

    @RequestMapping(method = RequestMethod.POST, value = "getOAFlowStatistics")
    public CommonResponse<SystemFlowStatisticsDto> getOAFlowStatistics(@RequestBody SystemFlowStatisticsSearchParamDto params) {
        logger.info("查询OA流程表单关联的系统编号,systemClassNo：{}", params.getSystemClassNoList());
        SystemFlowStatisticsDto oaFlowStatistics = flowService.getOAFlowStatistics(params);
        return CommonResponse.success(oaFlowStatistics);
    }

    /**
     * 根据ehr部门id查询oa的部门信息
     *
     * @param deptId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getOaDepartmentByEhrDepartment")
    public CommonResponse<Object> getOaDepartmentByEhrDepartment(@RequestParam(value = "deptId", required = false) String deptId,
                                                                 @RequestParam(value = "companyId", required = false) String companyId) {
        logger.info("getOaDepartmentByEhrDepartment,deptId：{},{}", deptId, companyId);
        if (!StringUtils.hasLength(deptId) && !StringUtils.hasLength(companyId)) {
            throw new IllegalArgumentException("参数不能同时为空");
        }
        return CommonResponse.success(flowService.getOaDepartmentByEhrDepartment(deptId, companyId));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getWCBBZJB")
    public CommonResponse<Object> getWCBBZJB(@RequestParam(value = "qqid", required = true) String qqid) {
        return CommonResponse.success(flowService.getWCBBZJB(qqid));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/switchDataSource")
    public CommonResponse<Object> switchDataSource() {
        return CommonResponse.success(switchDataSourceService.switchSecond());
    }

    @RequestMapping(method = RequestMethod.GET, value = "/switchDataSourcePrimary")
    public CommonResponse<Object> switchDataSourcePrimary() {
        return CommonResponse.success(switchDataSourceService.switchPrimary());
    }
}
